#include "findbar.h"
#include "../G/g.h"


FindBar::FindBar(QWidget *parent, Qt::WFlags f)
    : QFrame(parent, f) {
    // Layout;
    setVisible(false);
    QHBoxLayout *h = new QHBoxLayout(this);
    setLayout(h);

    
    QLabel *lblFind = new QLabel(tr("Fi&nd: "), this);
    find = new QLineEdit(this);
    lblFind->setBuddy(find);
    h->addWidget(lblFind);
    h->addWidget(find);
    connect(find, SIGNAL(textChanged(QString)), 
            this, SLOT(textChanged(QString)));
    old = QPalette(find->palette());
    find->setAutoFillBackground(true);

    findnext = new QPushButton("Find &Next", this);
    findprevious = new QPushButton("Find &Previous", this);
    matchcase = new QCheckBox("&Match Case", this);
    h->addWidget(findnext);
    h->addWidget(findprevious);
    h->addWidget(matchcase);
    h->addStretch();
    QAction *esc = new QAction("Escape", this);
    esc->setShortcut(tr("Esc"));
    connect(esc, SIGNAL(triggered()), this, SLOT(doEsc()));
    addAction(esc);
    find->installEventFilter(this);

    findnext->setFocusPolicy(Qt::NoFocus);
    findprevious->setFocusPolicy(Qt::NoFocus);
    matchcase->setFocusPolicy(Qt::NoFocus);
    connect(findnext, SIGNAL(clicked()), this, SLOT(doFindNext()));
    connect(findprevious, SIGNAL(clicked()), this, SLOT(doFindPrevious()));
    connect(matchcase, SIGNAL(stateChanged(int)), 
        this, SLOT(doStateChanged(int)));

    m_parent = parent;
    m_flags = f;
}

void FindBar::textChanged(QString) {
    m_search = find->text();
    if(!m_loading)
        emit(newSearchText(m_search, true, matchcase->checkState() == 
            Qt::Checked));
}

void FindBar::doFindNext() {
    emit(requestFindNext(matchcase->checkState() == Qt::Checked));
}

void FindBar::doFindPrevious() {
    emit(requestFindPrevious(matchcase->checkState() == Qt::Checked));
} 

void FindBar::load() {
    m_loading = true;
    find->clear();
    m_search.clear();
    find->setFocus();
    matchcase->setCheckState(Qt::Unchecked);
    find->setPalette(old);
    show();
    m_loading = false;
}

void FindBar::textFound(bool y) {
    if(y) {       
        find->setPalette(old);
    } else {
        QPalette pal;
        pal.setColor(QPalette::Text,QColor(Qt::white));
        pal.setColor(QPalette::Base,QColor(Qt::red));
        find->setPalette(pal);
    }
}

void FindBar::doEsc() {
    hide();
    emit(findBarHidden(isVisible()));
}

void FindBar::doStateChanged(int) {
    if(!m_loading) textChanged(find->text());
}
